package com.ls.lspicturebackend.manger.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.ls.lspicturebackend.config.CosClientConfig;
import com.ls.lspicturebackend.manger.CosManager;
import com.ls.lspicturebackend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

@Slf4j
public abstract class PictureUploadTemplate {
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 图片校验
        validPicture(inputSource);
        // 图片上传地址
        String uuid = RandomUtil.randomString(16);
        String dateTime = DateUtil.formatDate(new Date());
        String originalFilename = getOriginalFilename(inputSource);
        String pictureSuffix = FileUtil.getSuffix(originalFilename);
        String pictureName = String.format("%s_%s.%s", dateTime, uuid, pictureSuffix);
        if (pictureName.contains("?")) {
            pictureName = pictureName.split("\\?")[0];
        }
        String uploadPicturePath = String.format("/%s/%s", uploadPathPrefix, pictureName);
        // 建立临时图片
        File file = null;
        try {
            file = File.createTempFile(uploadPicturePath, null);
            processFile(inputSource, file);
            // 上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPicturePath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            List<CIObject> objectList = putObjectResult.getCiUploadResult().getProcessResults().getObjectList();
            if (!objectList.isEmpty()) {
                CIObject compressedCiObject = objectList.get(0);
                // 假如图片大小小于20kb那缩略图的地址就和压缩后图片地址一样
                CIObject thumbnailCiObject = compressedCiObject;
                if (objectList.size() > 1) {
                    thumbnailCiObject = objectList.get(1);
                }
                return buildResult(originalFilename, compressedCiObject, thumbnailCiObject);
            }
            return buildResult(imageInfo, uploadPicturePath, file, originalFilename);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 释放资源
            this.deleteTempleFile(file);
        }
    }

    private UploadPictureResult buildResult(String originFilename, CIObject compressedCiObject, CIObject thumbnailCiObject) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        // 设置图片为压缩后的地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        return uploadPictureResult;
    }


    private UploadPictureResult buildResult(ImageInfo imageInfo, String uploadPicturePath, File file, String originalFilename) {
        // 信息封装返回
        UploadPictureResult uploadPicture = new UploadPictureResult();
        int pictureWidth = imageInfo.getWidth();
        int pictureHeight = imageInfo.getHeight();
        double pictureScale = NumberUtil.round(pictureWidth * 1.0 / pictureHeight, 2).doubleValue();
        uploadPicture.setUrl(cosClientConfig.getHost() + "/" + uploadPicturePath);
        uploadPicture.setPicHeight(pictureHeight);
        uploadPicture.setPicWidth(pictureWidth);
        uploadPicture.setPicScale(pictureScale);
        uploadPicture.setPicSize(FileUtil.size(file));
        uploadPicture.setPicName(FileUtil.mainName(originalFilename));
        uploadPicture.setPicFormat(imageInfo.getFormat());
        return uploadPicture;
    }

    public abstract void processFile(Object inputSource, File file) throws Exception;

    public abstract void validPicture(Object inputSource);

    public abstract String getOriginalFilename(Object inputSource);

    public void deleteTempleFile(File file) {
        if (file == null) return;
        boolean delete = file.delete();
        if (!delete) {
            log.error("File delete error, filePath: {}", file.getAbsolutePath());
        }
    }
}
